package com.yncmcc.Mail;

import com.yncmcc.Entity.Contract;
import com.yncmcc.Entity.Employee;
import com.yncmcc.Exception.MailAddressException;
import com.yncmcc.Repository.Interface.ContractRepository;
import com.yncmcc.Repository.Interface.EmployeeRepository;
import com.yncmcc.Util.JavaMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by LiJiQiu on 2017/7/24.
 */
@Component
public class MailService {
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private EmployeeRepository employeeRepository;

    private JavaMail javaMail = new JavaMail();
    private Calendar specialDate = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    private String account;
    private String userName;
    private String password;
    private String host;

    public MailService() {
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setHost(String host) {
        this.host = host;
    }

    /**
     * 合同到期邮件提醒
     */
    public void remindToMail(){
        List<Contract> activeContract = contractRepository.getActiveContract();
        activeContract.stream().forEach(e -> {
            if (isRemind(e.getStage().getValue(), e.getStartDate())) {
                StringBuffer content = new StringBuffer();
                content.append("尊敬的" + e.getEmployeeName() + "先生/女士您好：\r\n");
                specialDate.setTime(new Date());
                //到期时间为提醒时间+1天
                specialDate.add(Calendar.DAY_OF_MONTH, 1);
                content.append("    您的合同 " + e.getContractName() + " （合同编号：" + e.getContractId() + "） 该阶段即将于" + sdf.format(specialDate.getTime()));
                content.append("到期，请您注意，谢谢。");
                //去除拟稿人姓名中的数字
                Employee employee = employeeRepository.getEmployeeByFullName(e.getEmployeeName().replaceAll("\\d+",""));
                try {
                    if (employee == null)
                        throw new NullPointerException("employee is null");
                } catch (Exception exception) {
                    exception.printStackTrace();
                    return;
                }
                //发送邮件
                sendMail(employee.getEmail(), "合同阶段到期提醒邮件", content.toString());
                //合同转入下一阶段，同时更新保存合同信息
                updateContractStage(e);
            }
        });
    }

    /**
     * 发送邮件
     * @param emailAddress
     * @param title
     * @param content
     */
    public void sendMail(String emailAddress, String title, String content){
        javaMail.initSender(host, account, userName, password);
        javaMail.initReceiver(emailAddress, title, content, false, "2000");
        try {
            javaMail.send();
        } catch (MailAddressException e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * 合同该阶段是否到达提醒时间
     * @param stage
     * @param startDate
     * @return
     */
    public boolean isRemind(int stage, Date startDate){
        String nowDate = sdf.format(new Date());
        specialDate.setTime(startDate);
        String remindDate = "";
        switch (stage) {
            //阶段一 有5天时间，提前一天提醒
            case 1 :
                specialDate.add(Calendar.DAY_OF_MONTH, 4);
                break;
            //阶段二 有3天时间，提前一天提醒
            case 2 :
                specialDate.add(Calendar.DAY_OF_MONTH, 2);
                break;
            //阶段三 有2天时间，提前一天提醒
            case 3 :
                specialDate.add(Calendar.DAY_OF_MONTH, 1);
                break;
            //阶段四 有3天时间，提前一天提醒
            case 4 :
                specialDate.add(Calendar.DAY_OF_MONTH, 2);
                break;
            //阶段一 有14天时间，提前一天提醒
            case 5 :
                specialDate.add(Calendar.DAY_OF_MONTH, 13);
                break;
            default:
        }
        remindDate = sdf.format(specialDate.getTime());
        return remindDate.equals(nowDate);
    }

    /**
     * 邮件提醒后，合同转入下一阶段，更新合同信息
     * @param contract
     */
    public void updateContractStage(Contract contract) {
        specialDate.setTime(contract.getStartDate());
        switch (contract.getStage().getValue()) {
            //阶段一 有5天时间
            case 1 :
                specialDate.add(Calendar.DAY_OF_MONTH, 5);
                contract.setStage(Contract.Stage.TWO);
                break;
            //阶段二 有3天时间
            case 2 :
                specialDate.add(Calendar.DAY_OF_MONTH, 3);
                contract.setStage(Contract.Stage.THREE);
                break;
            //阶段三 有2天时间
            case 3 :
                specialDate.add(Calendar.DAY_OF_MONTH, 2);
                contract.setStage(Contract.Stage.FOUR);
                break;
            //阶段四 有3天时间
            case 4 :
                specialDate.add(Calendar.DAY_OF_MONTH, 3);
                contract.setStage(Contract.Stage.FIVE);
                break;
            //阶段一 有14天时间
            case 5 :
                specialDate.add(Calendar.DAY_OF_MONTH, 14);
                contract.setStage(Contract.Stage.SIX);
                break;
            default:
                return;
        }
        contract.setStartDate(specialDate.getTime());
        contractRepository.saveAndFlush(contract);
    }
}
